﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="UnitOfWork.cs" company="emrecoskun.net">
//   ecblog.codeplex.com - emrecoskun.net
// </copyright>
// <summary>
//   The unit of work
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace EcBlog.Data.Sql.Base
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.Composition;
    using System.Linq;
    using System.Reflection;

    using EC.Models;

    using EcBlog.Data.Base;
    using EcBlog.Properties;

    /// <summary>
    /// The unit of work
    /// </summary>
    [InheritedExport, PartCreationPolicy(CreationPolicy.NonShared)]
    public abstract class UnitOfWork : IUnitOfWork
    {
        private readonly TransactionalDbContext context;
        private bool disposed;

        /// <summary>
        /// Initializes a new instance of the <see cref="UnitOfWork"/> class.
        /// </summary>
        /// <param name="context">The context.</param>
        protected UnitOfWork(TransactionalDbContext context)
        {
            this.context = context;
            this.context.Configuration.LazyLoadingEnabled = true;
            this.context.Configuration.ProxyCreationEnabled = false;
        }

        /// <summary>
        /// Gets the enum key value list.
        /// </summary>
        /// <typeparam name="TEnum">The type of the enum.</typeparam>
        /// <returns>
        /// The enum key value list
        /// </returns>
        public static List<KeyValue> GetEnumKeyValueList<TEnum>()
        {
            var keys = Enum.GetNames(typeof(TEnum));
            var values = Enum.GetValues(typeof(TEnum));
            return keys.Select((t, i) => new KeyValue { Key = t, Value = GetLocalizationName(values.GetValue(i).ToString()) }).ToList();
        }

        /// <summary>
        /// Gets the entity list with raw SQL.
        /// </summary>
        /// <typeparam name="TEnitity">The type of the enitity.</typeparam>
        /// <param name="query">The query.</param>
        /// <param name="parameters">The parameters.</param>
        /// <returns>
        /// The entity list
        /// </returns>
        public IEnumerable<TEnitity> GetWithRawSql<TEnitity>(string query, params object[] parameters) where TEnitity : class
        {
            return this.context.Database.SqlQuery<TEnitity>(query, parameters).ToList();
        }

        /// <summary>
        /// Saves all changes made in this context to the underlying database.
        /// </summary>
        public void Save()
        {
            // using (var scope = new TransactionScope(TransactionScopeOption.Required))
            // {
                this.context.SaveChanges();

            // scope.Complete();
            // }
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Creates the history repository.
        /// </summary>
        /// <typeparam name="TEntity">The type of the entity.</typeparam>
        /// <returns>
        /// The history repository
        /// </returns>
        public IHistoryRepository<TEntity> CreateHistoryRepository<TEntity>() where TEntity : class, new()
        {
            return new HistoryRepository<TEntity>(this.context);
        }

        /// <summary>
        /// Gets the enum key value list.
        /// </summary>
        /// <typeparam name="TEnum">The type of the enum.</typeparam>
        /// <returns>
        /// The enum key value list
        /// </returns>
        List<KeyValue> IUnitOfWork.GetEnumKeyValueList<TEnum>()
        {
            return GetEnumKeyValueList<TEnum>();
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    this.context.Dispose();
                }
            }

            this.disposed = true;
        }

        private static string GetLocalizationName(string name)
        {
            var property = typeof(ModelLocalization).GetProperty(name, BindingFlags.Static | BindingFlags.Public);
            return (string)property.GetValue(property.DeclaringType, null);
        }
    }
}